package list

import "sort"

// Problem Defintion: https://www.nowcoder.com/practice/50636077fde843c09bf915d0aef57a99?tpId=347&tqId=10091339

func selectKNums(nums []int, k, target int) int {
	sort.Ints(nums)
	low, high := 0, len(nums)-1

	var ret int
	for low <= high {
		mid := low + (high-low)/2
		l, r := max(0, mid-k+1), mid
		sum := sumRange(nums[l : r+1])
		if sum >= target {
			ret = nums[mid]
			high = mid - 1
		} else {
			low = mid + 1
		}
	}

	return ret
}

func sumRange(nums []int) (sum int) {
	for _, num := range nums {
		sum += num
	}

	return
}
